#include "e2d/core/physics/FixedJoint.h"
#include "e2d/core/physics/PxUtils.h"
#include "e2d/core/Entity.h"
#include "e2d/core/physics/RigidbodyDynamic.h"

using namespace physx;

e2d::FixedJoint::FixedJoint()
{
	m_LeftTransform.m_Position = { 1,1,1 };
	m_RightTransform.m_Position = { 1,1,1 };
}

void e2d::FixedJoint::OnLoad()
{
	m_Left.LoadFromScene(m_Entity->m_Scene);
	m_Right.LoadFromScene(m_Entity->m_Scene);

	bool flag1 = m_Left.m_Entity->HasComponent<e2d::RigidbodyDynamic>();
	bool flag2 = m_Right.m_Entity->HasComponent<e2d::RigidbodyDynamic>();

	if (!flag1 || flag2)
	{
		ztclog::info("failed init the fixed joint");
		return;
	}

	auto& rb1 = m_Left.m_Entity->Get<e2d::RigidbodyDynamic>();
	auto& rb2 = m_Right.m_Entity->Get<e2d::RigidbodyDynamic>();

	const auto leftPxTransform = e2d::PxUtils::toPxTransform(m_LeftTransform);
	const auto rightPxTransform = e2d::PxUtils::toPxTransform(m_RightTransform);

	Delete();

	m_PxFixedJoint = PxFixedJointCreate(*e2d::PxUtils::gPhysics,
		rb1.m_PxRgDynamic, leftPxTransform, rb2.m_PxRgDynamic, rightPxTransform);

};

void e2d::FixedJoint::Delete()
{
	if (m_PxFixedJoint)
		m_PxFixedJoint->release();
}
;


void e2d::FixedJoint::OnUpdateRuntime()
{
	
}

